package com.yhgarden.bbs.service.impl.common;

import com.yhgarden.bbs.service.api.common.WebSocketService;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArraySet;

//@Component
@Service
@ServerEndpoint("/websocket/{userId}")
//此注解相当于设置访问URL
public class WebSocketServiceImpl implements WebSocketService {

    private Session session;

    private static ConcurrentHashMap<String,WebSocketServiceImpl> webSockets =new ConcurrentHashMap<>();

    private static Map<String,Session> sessionPool = new HashMap<String,Session>();

    private String currentUser;

    @OnOpen
    public void onOpen(Session session, @PathParam(value="userId")String userId) {
        this.session = session;
        currentUser = userId;
        webSockets.put(currentUser,this);
        sessionPool.put(userId, session);
        System.out.println("【websocket消息】有新的连接，总数为:"+webSockets.size());
    }

    @OnClose
    public void onClose() {
        webSockets.remove(currentUser);
        System.out.println("【websocket消息】连接断开，总数为:"+webSockets.size());
    }

    @OnMessage
    public void onMessage(String message) {
        System.out.println("【websocket消息】收到客户端消息:"+message);
    }

    private void sendMessage(String message) throws IOException {
        this.session.getAsyncRemote().sendText(message);
    }


    // 此为广播消息
    @Override
    public void sendAllMessage(String message) {
        for(String key : webSockets.keySet()) {
            System.out.println("【websocket消息】广播消息:"+message);
            try {
                webSockets.get(key).sendMessage(message);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    // 此为单点消息
    @Override
    public void sendOneMessage(String userId, String message) {
        Session session = sessionPool.get(userId);
        if (session != null) {
            try {
                session.getAsyncRemote().sendText(message);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

}